import subprocess
import time
from pathlib import Path

import pyautogui
import pyperclip
from flask import Flask, jsonify, request
from src.models.response import Response

app = Flask(__name__)
# 配置数据库 URI，示例用 SQLite
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:your_password@localhost:3306/your_database'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False  # 关闭警告

@app.route('/mouse_position')
def mouse_position():
    _x, _y = pyautogui.position()
    return jsonify(Response(200, {"x": _x, "y": _y}, "success"))


@app.route('/input_message', methods=['POST'])
def input_message():
    data = request.json
    text = data.get("message", "")
    if not text:
        return jsonify(Response(400, None, "error"))
    pyperclip.copy(text)
    return jsonify(Response(200, None, "success"))


@app.route('/reload_weasel', methods=['POST'])
def reload_weasel():
    command = [f"C:\\Program Files\\Rime\\weasel-0.16.3\\WeaselServer.exe", '--reload']
    subprocess.Popen(command)
    return jsonify(Response(200, None, "success"))


@app.route('/update_weasel_custom_phrase', methods=['POST'])
def update_weasel_custom_phrase():
    data = request.get_json()
    if not isinstance(data, list):
        return jsonify({"code": 400, "msg": "Expected a JSON array"}), 400
    file_path = f"{Path.home()}\\AppData\\Roaming\\Rime\\custom_phrase.txt"
    print(file_path)
    try:
        with open(file_path, "w", encoding="utf-8", newline='') as f:
            for line in data:
                f.write(line+"\r\n")
        time.sleep(0.01)
        command = [f"C:\\Program Files\\Rime\\weasel-0.16.3\\WeaselServer.exe", '--reload']
        subprocess.Popen(command)
        return jsonify(Response(200, None, "success"))
    except Exception as e:
        return jsonify(Response(500, f"Error: {str(e)}", "success"))


if __name__ == '__main__':
    app.run(host="0.0.0.0", port=10002)
